package br.com.cfccultura.admin.view.tag.combo;

import java.util.List;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

public abstract class DefaultComboTag extends RequestContextAwareTag {
	
	private static final long serialVersionUID = -6634809175661799014L;
	
	private String styleId;
	private String title;
	private String selected;
	private String style;
	private String onchange;
	private Boolean disabled = false;
	
	protected void buildCombo(List<?> list, String labelProperty, String valueProperty) {
		try {
			StringBuilder html = new StringBuilder();
			html.append("<select ");
			html.append("id=\"").append(getStyleId()).append("\" ");
			html.append("name=\"").append(getStyleId()).append("\" ");
			html.append("title=\"").append(getTitle()).append("\" ");
			if(getDisabled())
				html.append("disabled ");
			if(getStyle() != null && !getStyle().equals(""))
				html.append("style=\"" + getStyle() + "\" ");
			if(getOnchange() != null && !getOnchange().equals(""))
				html.append("onchange=\"" + getOnchange() + "\" ");
			html.append(">");
			
			html.append("<option value=\"\">Selecione...</option>");
			for(Object obj : list) {
				String label = null;
				String value = null;
				if(labelProperty != null) {
					label = BeanUtils.getProperty(obj, labelProperty);					
				} else {
					if(obj instanceof Enum) {
						label = obj.toString();
					}
				}
				if(valueProperty != null) {
					value = BeanUtils.getProperty(obj, valueProperty);
				} else {
					if(obj instanceof Enum) {
						value = obj.toString();
					}
				}
				
				String selectedAttr = "";
				if(getSelected() != null && value.equals(getSelected())) {
					selectedAttr = "selected";
				}
				html.append("<option value=\"").append(value).append("\" ").append(selectedAttr).append(">").append(label).append("</option>");	
			}
			html.append("</select>");
			
			JspWriter out = pageContext.getOut();
			out.print(html);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected <T> T getBean(Class<T> klass) {
		return getRequestContext().getWebApplicationContext().getBean(klass);
	}
	
	public String getStyleId() {
		return styleId;
	}
	public void setStyleId(String styleId) {
		this.styleId = styleId;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSelected() {
		return selected;
	}
	public void setSelected(String selected) {
		this.selected = selected;
	}
	public Boolean getDisabled() {
		return disabled;
	}
	public void setDisabled(Boolean disabled) {
		this.disabled = disabled;
	}
	public String getStyle() {
		return style;
	}
	public void setStyle(String style) {
		this.style = style;
	}
	public String getOnchange() {
		return onchange;
	}
	public void setOnchange(String onchange) {
		this.onchange = onchange;
	}
}
